package com.yygo.dao.hibernate;

import com.yygo.dao.VehicleBrandDao;
import com.yygo.model.VehicleBrand;
import com.yygo.model.VehicleSeries;
import com.yygo.model.enums.CarType;
import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by tiansha on 2015/6/23.
 */
@Repository("vehicleBrandDao")
public class VehicleBrandDaoHibernate extends GenericDaoHibernate<VehicleBrand, Long> implements VehicleBrandDao {

    public VehicleBrandDaoHibernate() {
        super(VehicleBrand.class);
    }

    @Override
    public void clearAll() {
        List<VehicleBrand> list = super.getAll();
        for (VehicleBrand brand : list) {
            super.remove(brand);
        }

    }

    @Override
    public Set<VehicleSeries> getMySeries(String brandName, boolean isSecond) {
        Criteria criteria = getSession().createCriteria(VehicleSeries.class);
        List<CarType> carTypes = new ArrayList<CarType>();
        if (isSecond) {
            carTypes.add(CarType.new_and_old);
            carTypes.add(CarType.old_car);
        } else {
            carTypes.add(CarType.new_and_old);
            carTypes.add(CarType.new_car);
        }
        criteria.createCriteria("vehicleModels").add(Restrictions.in("carType", carTypes));
        criteria.createAlias("vehicleBrand", "brand").add(Restrictions.eq("brand.brand", brandName));
        List brands = criteria.list();
        return new HashSet<VehicleSeries>(brands);
    }

    @Override
    public Set<VehicleBrand> getAllBrands(boolean isSecond) {
        List<CarType> carTypes = new ArrayList<CarType>();
        if (isSecond) {
            carTypes.add(CarType.new_and_old);
            carTypes.add(CarType.old_car);
        } else {
            carTypes.add(CarType.new_and_old);
            carTypes.add(CarType.new_car);
        }
        List brands = getSession().createCriteria(VehicleBrand.class).createCriteria("vehicleSeries").createCriteria("vehicleModels").add(Restrictions.in("carType", carTypes)).list();
        return new HashSet<VehicleBrand>(brands);
    }
}
